package com.cl.base.auth.controller;

import cn.hutool.json.JSONUtil;
import com.cl.base.auth.dto.PayloadDto;
import com.cl.base.auth.entity.AuthUser;
import com.cl.base.auth.service.JwtTokenService;
import com.cl.base.constant.ResultCode;
import com.cl.base.util.ResultVo;
import com.cl.base.util.SecurityUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;

@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/user")
public class JwtTokenController {

    private final JwtTokenService jwtTokenService;
    private final AuthenticationManager authenticationManager;

    /**
     * 使用HMAC对称加密生成token
     *
     * @return R
     */
    @PostMapping("/login")
    public ResultVo generateTokenByHMAC(String username, String password) {
        UsernamePasswordAuthenticationToken upToken = new UsernamePasswordAuthenticationToken(username, password);
        try {
            Authentication authentication = authenticationManager.authenticate(upToken);
            SecurityUtil.setAuthentication(authentication);
        } catch (AuthenticationException e) {
            return ResultVo.resultVo(ResultCode.UNAME_PWD_ERROR);
        }
        AuthUser authUser = SecurityUtil.getLoginUser();

        PayloadDto payloadDto = jwtTokenService.createPayloadDto(authUser);
        String token = jwtTokenService.generateTokenByHMAC(JSONUtil.toJsonStr(payloadDto));
        HashMap<String, Object> rt = new HashMap<>();
        rt.put("token", token);
        return ResultVo.ok(rt);
    }

    /**
     * 验签
     *
     * @param token token
     * @return R
     */
    @PreAuthorize("@pms.hasPermission('sys_user_add')")
    @GetMapping(value = "/hmac/verify")
    public PayloadDto verifyTokenByHMAC(String token) {
        return jwtTokenService.getPayloadDtoByHMAC(token);
    }
}

